<?php

namespace App\Models;

use App\Util\Tool;
use App\Util\Url;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;

class ProductGoods extends Model
{
    protected $table = 'c_product_goods';

    public function branch()
    {
        return $this->hasOne('App\Models\BrandSort', 'id', 'product_brand_id');
    }

    public function category()
    {
        return $this->hasOne('App\Models\ProductSort', 'id', 'product_sort_id');
    }

    //工作室
    public function work()
    {
        return $this->hasOne('App\Models\DoctorWorks', 'id', 'supplier_work_id');
    }
    //供应商
    public function supplier()
    {
        return $this->belongsTo('App\Models\AdminUser', "supplier_work_id", 'id');
    }

    /****
     * @param $param
     * @return mixed
     * 商品列表
     */
    public function getGoodsList($param)
    {
        $where = [];
        if (isset($param['work_id']) && !empty($param['work_id'])) {  //医护室
            $where[] = ['c_work_relate_goods.work_id', '=', $param['work_id']];
        }
        if (isset($param['category_id']) && !empty($param['category_id'])) {  //分类id
            $where[] = ['c_work_relate_goods.cate_id', '=', $param['category_id']];
        }
        if (isset($param['branch_id']) && !empty($param['branch_id'])) {  //品牌id
            $where[] = ['c_product_goods.product_brand_id', '=', $param['branch_id']];
        }
        if (isset($param['title']) && !empty($param['title'])) {  //标题
            $where[] = ['c_product_goods.product_name', 'like', '%' . $param['title'] . '%'];
        }
        $where[] = ["c_product_goods.product_audit_status", "=", 2]; //审核通过
        $where[] = ["c_product_goods.product_racking", "=", 2]; //上架
        $where[] = ["c_work_relate_goods.is_online", "=", 1]; //上架
        $work_relate_work = new WorkRelateGoods();
        $goods = $work_relate_work->join('c_doctor_works', 'c_doctor_works.id', '=', 'c_work_relate_goods.work_id')
            ->select("c_product_goods.*")
            ->addSelect("c_doctor_works.work_name", "c_work_relate_goods.work_id", "c_work_relate_goods.id as relate_id")
            ->join('c_product_goods', 'c_product_goods.id', '=', 'c_work_relate_goods.goods_id')
            ->orderBy("id", "desc")
            ->where($where)
            ->simplePaginate();
        if (!empty($goods)) {
            $goods = $goods->toArray();
            foreach ($goods['data'] as $kk => $vv) {
                $goods['data'][$kk]['product_image'] = env("APP_URL") . '/upload/' . $vv['product_image'];
                $goods['data'][$kk]['product_detail_image_one'] = env("APP_URL") . '/upload/' . $vv['product_detail_image_one'];
                $goods['data'][$kk]['product_detail_image_two'] = env("APP_URL") . '/upload/' . $vv['product_detail_image_two'];
                $goods['data'][$kk]['product_detail_image_three'] = env("APP_URL") . '/upload/' . $vv['product_detail_image_three'];
                $goods['data'][$kk]['product_detail_image_four'] = env("APP_URL") . '/upload/' . $vv['product_detail_image_four'];
                $goods['data'][$kk]['product_detail_image_five'] = env("APP_URL") . '/upload/' . $vv['product_detail_image_five'];
                $goods['data'][$kk]['product_rests_image'] = env("APP_URL") . '/upload/' . $vv['product_rests_image'];
                $goods['data'][$kk]['branch_name'] = (new BrandSort())->where("id","=",$vv['product_brand_id'])->value("brand_name");
                $goods['data'][$kk]['sort_name'] = (new ProductSort())->where("id","=",$vv['product_sort_id'])->value("sort_name");
            }
        }
        return $goods;
    }

    /**
     * @param $param
     * @return mixed
     * 康养产品修改,通过一级分类查询子集分类
     */
    public function getChildCateId($param)
    {
        return (new ProductSort())->where([['pid', '=', $param['cate_id']]])->pluck("id")->toArray();
    }



    /****
     * @param $param
     * @return mixed
     * 获取康养商品列表
     */
    public function getHealthGoodsList($param)
    {
        $w = [];
        $where = [];
        if (isset($param['cate_id'])) {
            $childIds  = $this->getChildCateId($param);
            if (!empty($childIds)) {
                $w[] = [function ($query) use ($childIds) {
                    $query->whereIn('c_product_goods.product_sort_id', $childIds);
                }];
            }
//            $w[] = ["c_product_goods.product_sort_id", "=", $param['cate_id']];
        }
        if (isset($param['title'])) {
            $w[] = ['c_product_goods.product_name', 'like', '%' . $param['title'] . '%'];
        }
        //获取康养商品的工作室列表
        $work_ids = $this->getWorksIdList($param);
        if (!empty($work_ids)) {
            $where[] = [function ($query) use ($work_ids) {
                $query->whereIn('id', $work_ids);
            }];
        }
        $w[] = ["c_product_goods.product_audit_status", "=", 2]; //审核通过
        $w[] = ["c_product_goods.product_racking", "=", 2];
        $w[] = ["c_work_relate_goods.is_online", "=", 1];
        $res = (new DoctorWorks())->orderbyDesc("id")->where($where)->get();
        $work_relate_work = new WorkRelateGoods();
        $order = new Order();
        foreach ($res as $k => $val) {
            $ww = [];
            $ww[] = ['c_work_relate_goods.work_id','=',$val->id];
            $goods  = $work_relate_work->join('c_doctor_works', 'c_doctor_works.id', '=', 'c_work_relate_goods.work_id')
                ->select("c_product_goods.*")
                ->addSelect("c_doctor_works.work_name")
                ->addSelect("c_work_relate_goods.id as relate_id")
                ->addSelect("c_work_relate_goods.work_id as work_id")
                ->join('c_product_goods', 'c_product_goods.id', '=', 'c_work_relate_goods.goods_id')
                ->orderBy("c_product_goods.id", "desc")
                ->where($w)
                ->where($ww)
                ->get();
            if(!empty($goods)){
                foreach($goods as $kk=>$vv){
                    $goods[$kk]->product_image = env("APP_URL").'/upload/'.$vv->product_image;
                    $goods[$kk]->product_detail_image_one = env("APP_URL").'/upload/'.$vv->product_detail_image_one;
                    $goods[$kk]->product_detail_image_two = env("APP_URL").'/upload/'.$vv->product_detail_image_two;
                    $goods[$kk]->product_detail_image_three = env("APP_URL").'/upload/'.$vv->product_detail_image_three;
                    $goods[$kk]->product_detail_image_four = env("APP_URL").'/upload/'.$vv->product_detail_image_four;
                    $goods[$kk]->product_detail_image_five = env("APP_URL").'/upload/'.$vv->product_detail_image_five;
                    $goods[$kk]->product_rests_image = env("APP_URL").'/upload/'.$vv->product_rests_image;
                    $goods[$kk]->branch_name = (new BrandSort())->where("id","=",$vv->product_brand_id)->value("brand_name");
                    $goods[$kk]->sort_name = (new ProductSort())->where("id","=",$vv->product_sort_id)->value("sort_name");
                }
            }
            $tool = new Tool();
            if (!empty($val->work_detail)) {
                $res[$k]->work_detail = $tool->addHostToImage($val->work_detail);
            }
            $res[$k]->health_goods = $goods;
            //获取工作室销量
            $res[$k]->sale_num = $order->where([['work_id','=',$val->id],['order_status','=',1]])->count("id");
//            $res[$k]->health_goods = $this->where([['work_id', '=', $val->id]])->where($w)->orderByDesc("id")->skip(0)->take(4)->get();
        }
        return !empty($res) ? $res->toArray() : [];
    }

    /****
     * @return array
     * 康养产品分类
     */
    public function getHealthCategoryList()
    {
        //获取康养商品的分类id
//        $cateIds = $this->getCateIdsByHealth();
//        //获取康养商品的分类列表
//        $cateList = $this->getCategoryList($cateIds);

        //获取一级分类
        $cateList =  (new ProductSort())->orderByDesc('id')->where([['pid','=',0]])->get();
        return !empty($cateList) ? $cateList->toArray() : [];
    }


    /***
     * @return mixed
     * 获取分类ID
     */
    public function getCateIdsByHealth()
    {
        $workrelategoods = new WorkRelateGoods();
        return  $workrelategoods->getCateIdsByHealth();
//        return $this->distinct()->where([["is_health", "=", 1]])->pluck("product_sort_id");
    }

    /****
     * @param $ids
     * @return mixed
     * 获取分类列表
     */
    public function getCategoryList($ids)
    {
        $where[] = [function ($query) use ($ids) {
            $query->whereIn('id', $ids);
        }];
        return (new ProductSort())->orderByDesc('id')->where($where)->get();
    }

    /***
     * @param $ids
     * @return mixed
     * 获取工作室ID列表
     */
    public function getWorksIdList($param)
    {
        $w = [];
        $work_relate_work = new WorkRelateGoods();
        if (isset($param['cate_id'])) {
            $childIds  = $this->getChildCateId($param);
            if (!empty($childIds)) {
                $w[] = [function ($query) use ($childIds) {
                    $query->whereIn('c_product_goods.product_sort_id', $childIds);
                }];
            }
//            $w[] = ["c_product_goods.product_sort_id", "=", $param['cate_id']];
        }
        if (isset($param['title'])) {
            $w[] = ['c_product_goods.product_name', 'like', '%' . $param['title'] . '%'];
        }
        $res = $work_relate_work
//            ->join('c_doctor_works', 'c_doctor_works.id', '=', 'c_work_relate_goods.work_id')
//            ->select("c_product_goods.*")
//            ->addSelect("c_doctor_works.work_name")
//            ->addSelect("c_work_relate_goods.id as relate_id")
            ->join('c_product_goods', 'c_product_goods.id', '=', 'c_work_relate_goods.goods_id')
            ->where($w)
            ->where([['c_product_goods.product_racking','=',2],['c_product_goods.product_audit_status','=',2],['c_work_relate_goods.is_online','=',1]])
            ->distinct()
            ->pluck("c_work_relate_goods.work_id");
        return $res;
//        return $work_relate_work->distinct()->where($where)->pluck("work_id");
//        return $this->groupBy('work_id')->where([["is_health", "=", 1]])->where($where)->pluck("work_id");
    }

    /***
     *
     * 获取商品详情
     */
    public function getGoodsDetail($filter)
    {
        $info = $this->where([['id', '=', $filter['goods_id']]])->first();
        $info->product_rests_image =  empty($info->product_rests_image)?$info->product_rests_image:"";
        $info->nohost_product_image =  empty($info->product_image)?$info->product_image:"";
        $info->nohost_product_detail_image_one =  empty($info->product_detail_image_one)?$info->product_detail_image_one:"";
        $info->nohost_product_detail_image_two =  empty($info->product_detail_image_two)?$info->product_detail_image_two:"";
        $info->nohost_product_detail_image_three =  empty($info->product_detail_image_three)?$info->product_detail_image_three:"";
        $info->nohost_product_detail_image_four =  empty($info->product_detail_image_four)?$info->product_detail_image_four:"";
        $info->nohost_product_detail_image_five =  empty($info->product_detail_image_five)?$info->product_detail_image_five:"";
        $info->nohost_product_rests_image =  empty($info->product_rests_image)?$info->product_rests_image:"";
        $info->product_image =!empty($info->product_image)? env('APP_URL') . '/upload/' . $info->product_image:"";
        $info->product_detail_image_one = !empty($info->product_detail_image_one)? env('APP_URL') . '/upload/' . $info->product_detail_image_one:"";
        $info->product_detail_image_two = !empty($info->product_detail_image_two)? env('APP_URL') . '/upload/' . $info->product_detail_image_two:"";
        $info->product_detail_image_three =!empty($info->product_detail_image_three)? env('APP_URL') . '/upload/' . $info->product_detail_image_three:"";
        $info->product_detail_image_four =!empty($info->product_detail_image_four)? env('APP_URL') . '/upload/' . $info->product_detail_image_four:"";
        $info->product_detail_image_five = !empty($info->product_detail_image_five)?env('APP_URL') . '/upload/' . $info->product_detail_image_five:"";
        $info->product_rests_image =!empty($info->product_rests_image)? env('APP_URL') . '/upload/' . $info->product_rests_image:"";
        $info->branch_name = (new BrandSort())->where("id","=",$info->product_brand_id)->value("brand_name");
        $info->category_name = (new ProductSort())->where("id","=",$info->product_sort_id)->value("sort_name");
        $host = new Url();
        $tool = new Tool();
        //判断商品来源
        if($info->product_source ==1){ //工作室
            $info->source = (new DoctorWorks())->where([["id",'=',$info->supplier_work_id]])->first();
            $info->source->province = Area::getNameByCode($info->source->province_id);
            $info->source->city = Area::getNameByCode($info->source->city_id);
            $info->source->district = Area::getNameByCode($info->source->district_id);
        }elseif ($info->product_source ==2){ //供应商
            $info->source = (new AdminUser())->where([["id",'=',$info->supplier_work_id]])->first();
            $tt['type'] = 3;
            $tt['user_id'] = $info->supplier_work_id;
            $im_inf = Tool::getUserNameForIm($tt);
            $info->supplier_im_username = $im_inf['username']; //供应商id
        }
        if (isset($filter['work_id'])) {
            $works_detail = (new DoctorWorks())->where([['id', '=', $filter['work_id']]])->first();
            $info->self_work_info = $works_detail->work_name;
            $docry = (new Doctor())->where([['work_id','=', $filter['work_id']]])->first();
            //获取环信信息
            $ts['type'] = 2;
            $ts['user_id'] = $docry->id;
            $im_info = $tool::getUserNameForIm($ts);
            $info->im_username =$im_info['username']; //工作室im
        }
        $info->is_collect = 0;
        if (isset($filter['user_id'])) {
            if(isset($filter['goods_id']) && isset($filter['types']) && $filter['types'] ==2 ){ //医护端
                //判断是否收藏
                $is_has = (new CourseCollect())
                    ->where([['user_id', '=', $filter['user_id']], ['course_id', '=', $filter['goods_id']],['collect_type','=',2],['type','=',2]])
                    ->first();
                if ($is_has) {
                    $info->is_collect = 1;
                }
            }else{ //用户端需要足迹
                //添加足迹
                $dd['goods_id'] = $filter['goods_id'];
                $dd['user_id'] = $filter['user_id'];
                $dd['work_id'] = $filter['work_id'];
                $dd['type'] = 2;
                (new Footprint())->addFootPrint($dd);
                //判断是否收藏
                $is_has = (new CourseCollect())
                    ->where([['user_id', '=', $filter['user_id']], ['course_id', '=', $filter['goods_id']],['collect_type','=',1]])
                    ->first();
                if ($is_has) {
                    $info->is_collect = 1;
                }
            }
        }
        $info->self_cate_id = (new WorkRelateGoods())
            ->where([['work_id', '=', $filter['work_id']], ['goods_id', '=', $filter['goods_id']]])
            ->value("cate_id");
        if (!empty($info->self_cate_id)) {
            $info->self_cate_name = (new WorkRoomSortCategory())
                ->where([['id', '=', $info->self_cate_id]])->value("classify_name");
        }else{
            $info->self_cate_name = "";
        }
        $info->self_cate_id = (new WorkRelateGoods())
            ->where([['work_id','=',$filter['work_id']],['goods_id','=',$filter['goods_id']]])
            ->value("cate_id");
        //获取精选口碑
        $info->evaluate =  (new Evaluate())->with(['user'])
            ->where([['goods_id','=', $filter['goods_id']],['score','=',5],['types','=',2]])
            ->orderByDesc("id")->first();
        if(!empty($info->evaluate)){
            if (isset($info->evaluate->images)){
                $info->evaluate->images =$tool->addHostToImage($info->evaluate->images);
            }
            if (isset($info->evaluate->videos)) {
                $info->evaluate->videos = $tool->addHostToImage($info->evaluate->videos);
            }
            $info->evaluate->user->image = $host::getHttpHost() . 'upload/' . $info->evaluate->user->image;
            $info->evaluate->eval_time =$tool::time2Units(time() - strtotime($info->evaluate->created_at));
        }
        return $info->toArray();
    }

    /***
     *
     * 获取商品详情
     */
    public function getInfo($filter)
    {
        $info = $this->where([['id', '=', $filter['goods_id']]])->first();
        if (!empty($info)) {
            return $info->toArray();
        }
        return [];
    }


    /**
     * @param $filter
     * 添加商品关联
     */
    public function addRelateGoods($filter)
    {
        $goods_ids = Tool::handelString($filter['goods_ids']);
        if (empty($goods_ids)) {
            return "商品ID不能为空";
        }
        $relate = new WorkRelateGoods();
        $data = [];
        $log = new SelectedGoodsLog();
        $goods_ids = array_unique($goods_ids);
        foreach ($goods_ids as $k => $v) {
            $dd = $relate->where([['goods_id', '=', $v], ['work_id', '=', $filter['work_id']], ['cate_id', '=', $filter['cate_id']]])->first();
            $log::where([['goods_id','=',$v],['work_id','=',$filter['work_id']],['type','=',1]])->delete();
            if ($dd) {
                continue;
            }
            $data[$k]['goods_id']  = $v;
            $data[$k]['work_id']  = $filter['work_id'];
            $data[$k]['cate_id']  =  $filter['cate_id'];
            $data[$k]['created_at']  =  date("Y-m-d H:i:s",time());
            $data[$k]['updated_at']  =  date("Y-m-d H:i:s",time());
        }
        $yes = DB::table('c_work_relate_goods')->insert($data);
        if($yes){
            return true;
        }
        return "添加失败";
    }

    public function getChildCate($pid)
    {
        return (new ProductSort())->where([['pid','=',$pid]])->pluck("id");
    }



    /***
     *
     * 选品库
     */
    public function getAllGoodsList($param)
    {
        $where[] = ['product_audit_status','=',2];
        $where[] = ['product_racking','=',2];
        $where[] = ['product_source','=',2]; //供应商
        $field = "id";
        $sort = "desc";
        //查看工作室已有选品库
        $ids = (new WorkRelateGoods())::getGoodsIds($param);
        $selected_ids = (new SelectedGoodsLog())::getSelectedArticleIds($param,1);
        if (!empty($selected_ids)) {
            $selected_ids = $selected_ids->toArray();
        } else {
            $selected_ids = [];
        }
        if (isset($param['product_sort_id'])) {
            //分类id
            $childs = $this->getChildCate($param['product_sort_id'])->toArray();
            array_push($childs, $param['product_sort_id']);
            $where[] = [function ($query) use ($childs) {
                $query->whereIn('product_sort_id', $childs);
            }];
        }
//        if (isset($param['art_types'])) {  //文章类型
//            $where[] = ['art_types', '=', $param['art_types']];
//        }
        if (isset($param['title'])) {  //标题搜索
            $where[] = ['product_name', 'like', '%' . $param['title'] . '%'];
        }
        if (isset($param['hot']) && $param['hot'] == 1) { //销量
            $field = "product_sales";
            $sort = "desc";
        } else if (isset($param['hot']) && $param['hot'] == 2) {
            $field = "product_sales";
            $sort = "asc";
        }
        $res = $this->where($where)->whereNotIn('id', $ids)->orderBy($field, $sort)->get();
        if (!empty($res)) {
            $result = $res->toArray();
            $host = new  Url();
            $productSort = new ProductSort();
            foreach ($result as $k => &$v) {
                if (in_array($v['id'], $selected_ids)) {
                    $v['selected'] = 1;
                } else {
                    $v['selected'] = 0;
                }
                $v['product_image'] = $host::getHttpHost() . 'upload/' . $v['product_image'];
                $v['sort_name'] = $productSort->where([['id','=',$v['product_sort_id']]])->value("sort_name");
            }
            return $result;
        }
        return [];
    }


    /***
     * @param $filter
     * 医护中心商品管理列表(医护端)
     */
    public function getWorkroomGoods($filter)
    {
        $where = [];
        $w[] = ['supplier_work_id', '=', $filter['work_id']];
        $w[] = ['product_source', '=', 1];
        if (!isset($filter['audit_status'])) { //审核中不需要走这
            $relatGoodsIds = self::getRelatGoodsIds($filter);
            if (!empty($relatGoodsIds)) {
                $where[] = [function ($query) use ($relatGoodsIds) {
                    $query->whereIn('id', $relatGoodsIds);
                }];
            }
        }
        $allGoodsIds = self::getAllNumber($filter);
        if (!empty($allGoodsIds)) {
            $allWhere[] = [function ($query) use ($allGoodsIds) {
                $query->whereIn('id', $allGoodsIds);
            }];
        }
        //商品总数
        $count = $this->where($w)->distinct()
            ->orWhere($allWhere)
            ->count();
        if (isset($filter['audit_status']) && $filter['audit_status'] == 0) {  //审核中
            $w[] = ["product_audit_status", "=", 0];
        }
        if (isset($filter['online']) && $filter['online'] == 1) {  //上架
            $w[] = ["product_racking", "=", 2];
            $w[] = ["product_audit_status", "=", 2];
        } else if (isset($filter['online']) && $filter['online'] == 2) {  //下架
            $w[] = ["product_racking", "=", 1];
            $w[] = ["product_audit_status", "=", 2];
        }
        if (isset($filter['title'])) {   //标题搜索
            $w[] = ['product_name', 'like', '%' . $filter['title'] . '%'];
        }
        $result = $this->where($w)->distinct()
            ->orWhere($where)->orderBy("id", "desc")
            ->simplePaginate();
        if (!empty($result)) {
            $res = $result->toArray();
            $res['all_nums'] = $count;
            $relate = new WorkRelateGoods();
            $host = new Url();
            foreach ($res['data'] as $k => &$v) {
                $v['product_image'] = $host::getHttpHost() . 'upload/' . $v['product_image'];
                if ($v['product_source'] == 2) {
                    $v['relate_goods'] = $relate->where([['work_id', '=', $filter['work_id']], ['goods_id', '=', $v['id']]])->first()->toArray();
                }
            }
            return $res;
        }
        return [];
    }

    /**
     * @param $work_id
     * 获取关联表中的
     */
    public function getRelatGoodsIds($param)
    {
        $w = [];
        $work_relate_work = new WorkRelateGoods();
        if (isset($param['online']) && $param['online'] == 1) {
            $w[] = ["c_work_relate_goods.is_online", "=", 1];
        }else if (isset($param['online']) && $param['online'] == 2){
            $w[] = ["c_work_relate_goods.is_online", "=", 0];
        }
        if (isset($param['title'])) {
            $w[] = ['c_product_goods.product_name', 'like', '%' . $param['title'] . '%'];
        }
        $res = $work_relate_work
            ->join('c_product_goods', 'c_product_goods.id', '=', 'c_work_relate_goods.goods_id')
            ->where($w)
            ->where([['c_product_goods.product_racking','=',2],
                ['c_product_goods.product_audit_status','=',2],
                ['c_work_relate_goods.work_id','=',$param['work_id']]])
            ->distinct()
            ->pluck("c_work_relate_goods.goods_id");
        return $res;
    }


    public function getAllNumber($param)
    {
        $work_relate_work = new WorkRelateGoods();
        $res = $work_relate_work
            ->join('c_product_goods', 'c_product_goods.id', '=', 'c_work_relate_goods.goods_id')
            ->where([['c_product_goods.product_racking','=',2],
                ['c_product_goods.product_audit_status','=',2],
                ['c_work_relate_goods.work_id','=',$param['work_id']]])
            ->distinct()
            ->pluck("c_work_relate_goods.goods_id");
        return $res;
    }


    /**
     * @param $param
     * 商品上下架
     */
    public function setWorkroomGoodsRack($param)
    {
        $info = $this->getInfo($param);
        if ($info['product_source'] == 1) { //工作室
//            if ($info['supplier_work_id'] != $param['work_id']) {
//                return "该订单为供应商订单,您无权修改!";
//            }
            if ($info['product_racking'] == 1) {
                $res = DB::table("c_product_goods")->where([['id', '=', $param['goods_id']]])->update(['product_racking' => 2]);
            } else {
                $res = DB::table("c_product_goods")->where([['id', '=', $param['goods_id']]])->update(['product_racking' => 1]);
            }
            if ($res) {
                return true;
            } else {
                return "修改失败!";
            }
        } else { //供货商
//            if ($info['supplier_work_id'] == $param['work_id']) {
//                return "该订单为自营订单,参数错误!";
//            }
            $relates = (new WorkRelateGoods())->where([['work_id', '=', $param['work_id']], ['goods_id', '=', $param['goods_id']]])->first();
//            dd($relates);
            if ($relates->is_online == 1) {
                $relates->is_online = 0;
                return $relates->save();
            } else {
                $relates->is_online = 1;
                return $relates->save();
            }
        }
    }

    /**
     * @param $data
     * @return array|string
     * 发布商品
     */
    public function add($data)
    {
        try {
            DB::beginTransaction(); // 开始事务
//                更新
            if (isset($data['goods_id']) && !empty($data['goods_id'])) {
                $redata = $this->where([['id','=',$data['goods_id']]])->first();
                $redata->product_name = isset($data['product_name']) ? $data['product_name'] : $redata->product_name;
                $redata->product_unit = isset($data['product_unit']) ? $data['product_unit'] : $redata->product_unit;
                $redata->product_sort_id = isset($data['product_sort_id']) ? $data['product_sort_id'] : $redata->product_sort_id;
                $redata->product_brand_id = isset($data['product_brand_id']) ? $data['product_brand_id'] : $redata->product_brand_id;
                $redata->product_image = isset($data['product_image']) ? $data['product_image'] : $redata->product_image;
                $redata->product_standard = isset($data['product_standard']) ? $data['product_standard'] : $redata->product_standard;
                $redata->product_remark = isset($data['product_remark']) ? $data['product_remark'] : $redata->product_remark;
                $redata->product_rests_image = isset($data['product_rests_image']) ? $data['product_rests_image'] : $redata->product_rests_image;
                $redata->product_retail_price = isset($data['product_retail_price']) ? $data['product_retail_price'] : $redata->product_retail_price;
                $redata->product_original_price = isset($data['product_original_price']) ? $data['product_original_price'] : $redata->product_original_price;
                $redata->product_cost_price = isset($data['product_cost_price']) ? $data['product_cost_price'] : $redata->product_cost_price;
                $redata->product_label = isset($data['product_label']) ? $data['product_label'] : $redata->product_label;
                $redata->product_coding = isset($data['product_coding']) ? $data['product_coding'] : $redata->product_coding;
                $redata->product_bar_code = isset($data['product_bar_code']) ? $data['product_bar_code'] : $redata->product_bar_code;
                $redata->product_stock = isset($data['product_stock']) ? $data['product_stock'] : $redata->product_stock;
                $redata->product_param = isset($data['product_param']) ? $data['product_param'] : $redata->product_param;
                $redata->product_add_user_id = isset($data['product_add_user_id']) ? $data['product_add_user_id'] : $redata->product_add_user_id;
                $redata->supplier_work_id = isset($data['supplier_work_id']) ? $data['supplier_work_id'] : $redata->supplier_work_id;
                $redata->product_detail_image_one = isset($data['product_detail_image_one']) ? $data['product_detail_image_one'] : $redata->product_detail_image_one;
                $redata->product_detail_image_two = isset($data['product_detail_image_two']) ? $data['product_detail_image_two'] : $redata->product_detail_image_two;
                $redata->product_detail_image_three = isset($data['product_detail_image_three']) ? $data['product_detail_image_three'] : $redata->product_detail_image_three;
                $redata->product_detail_image_four = isset($data['product_detail_image_four']) ? $data['product_detail_image_four'] : $redata->product_detail_image_four;
                $redata->product_detail_image_five = isset($data['product_detail_image_five']) ? $data['product_detail_image_five'] : $redata->product_detail_image_five;
                $this->addWorkRelateGoods($data,$data['goods_id']);
                $res = $redata->save();
            } else {
                //添加
                $this->product_name = $data['product_name'];
                $this->product_unit = $data['product_unit'];
                $this->product_sort_id = $data['product_sort_id'];
                $this->product_brand_id = isset($data['product_brand_id'])?$data['product_brand_id']:0;
                $this->product_image = isset($data['product_image'])?$data['product_image']:"";
                $this->product_standard = isset($data['product_standard'])?$data['product_standard']:"";
                $this->product_remark = isset($data['product_remark'])?$data['product_remark']:"";
                $this->product_rests_image = isset($data['product_rests_image'])?$data['product_rests_image']:"";
                $this->product_retail_price = isset($data['product_retail_price'])?$data['product_retail_price']:"";
                $this->product_original_price = isset($data['product_original_price'])?$data['product_original_price']:"";
                $this->product_cost_price = isset($data['product_cost_price'])?$data['product_cost_price']:"";
                $this->product_label = isset($data['product_label'])?$data['product_label']:"";
                $this->product_coding = isset($data['product_coding'])?$data['product_coding']:"";
                $this->product_bar_code = isset($data['product_bar_code'])?$data['product_bar_code']:"";
                $this->product_add_type = 1;
                $this->product_stock = isset($data['product_stock'])?$data['product_stock']:0;
                $this->product_param = isset($data['product_param'])?$data['product_param']:"";
                $this->product_source = 1;
                $this->product_add_user_id = isset($data['product_add_user_id'])?$data['product_add_user_id']:0;
                $this->supplier_work_id = isset($data['supplier_work_id'])?$data['supplier_work_id']:0;
                $this->product_detail_image_one =isset($data['product_detail_image_one']) ? $data['product_detail_image_one']:"";
                $this->product_detail_image_two = isset($data['product_detail_image_two']) ? $data['product_detail_image_two']:"";
                $this->product_detail_image_three = isset($data['product_detail_image_three']) ?$data['product_detail_image_three']:"";
                $this->product_detail_image_four = isset($data['product_detail_image_four']) ?$data['product_detail_image_four']:"";
                $this->product_detail_image_five = isset($data['product_detail_image_five']) ?$data['product_detail_image_five']:"";
                $res = $this->save();
                $this->addWorkRelateGoods($data,$this->id);
            }
            if ($res) {
                DB::commit(); // 提交事务
                return ['goods_id' => $this->id ?: $data['goods_id']];
            } else {
                return '入驻失败';
                DB::rollback(); // 回滚事务
            }
        } catch (Exception $e) {
            DB::rollback(); // 回滚事务
        }
    }


    /**
     * @param $data
     * @param $art_id
     * @return bool
     * 添加商品关联自己工作室的分类
     * c_work_relate_courses
     */
    public function addWorkRelateGoods($data, $course_id)
    {
        $relate = new WorkRelateGoods();
        $res = $relate->where([['work_id', '=', $data['supplier_work_id']], ['goods_id', '=', $course_id]])->first();
        if ($res) {
            if ($res->cate_id != $data['self_cate_id']) { //分类ID不同,修改分类
                $res->cate_id = $data['self_cate_id'];
                return $res->save();
            }
            return true;
        }
        //添加
        $relate->cate_id = $data['self_cate_id'];
        $relate->work_id = $data['supplier_work_id'];
        $relate->goods_id = $course_id;
        return $relate->save();
    }



    /**
     * @param $data
     * 删除商品
     */
    public function delGoods($param)
    {
        $info = $this->getInfo($param);
        if (!$info) {
            return "该商品不存在!";
        }
        if ($param['source_type'] == 1) { //工作室
            if ($info['supplier_work_id'] != $param['work_id']) {
                return "该商品不是该工作室商品,您无权修改!";
            }
            $res = (new OrderGoods())->where([['goods_id', '=', $param['goods_id']], ['work_id', '=', $param['work_id']], ['goods_type', '=', 2]])->first();
            if ($res) {
                return "该商品已存在订单记录,不能删除!";
            }
            $del = $this::destroy($param['goods_id']);
            if ($del) {
                (new WorkRelateGoods())->where([['goods_id', '=', $param['goods_id']]])->delete();
                (new CourseCollect())->where([['type','=',2],['course_id','=',$param['goods_id']]])->delete();
                return true;
            }
            return "删除失败!";
        } else { //供货商产品删除关联
            $relates = (new WorkRelateGoods())->where([['work_id', '=', $param['work_id']], ['goods_id', '=', $param['goods_id']]])->delete();
            if ($relates) {
                return true;
            }
            return "删除失败!";
        }
    }

    /***
     * @param $param
     * @return array
     * 获取产品信息
     */
    public function getGoods($param)
    {
        $res = $this->getInfo($param);
        $host = new Url();
        $res['product_image'] = $host::getHttpHost() . 'upload/' . $res['product_image'];
        $res['product_detail_image_one'] = $host::getHttpHost() . 'upload/' . $res['product_detail_image_one'];
        $res['product_detail_image_two'] = $host::getHttpHost() . 'upload/' . $res['product_detail_image_two'];
        $res['product_detail_image_three'] = $host::getHttpHost() . 'upload/' . $res['product_detail_image_three'];
        $res['product_detail_image_four'] = $host::getHttpHost() . 'upload/' . $res['product_detail_image_four'];
        $res['product_detail_image_five'] = $host::getHttpHost() . 'upload/' . $res['product_detail_image_five'];
        $res['product_rests_image'] = $host::getHttpHost() . 'upload/' . $res['product_rests_image'];
        return $res;
    }


}
